<?php
    class Response{
        protected $request;
        protected static $response_format = <<< EOL
HTTP/1.1 %d %s
Server: PHP-SCRIPT
Date: %s GMT
Content-Type: text/html
Last-Modified: %s GMT
Cache-control: no-cache
Pragma= no-cache
Expires = -1
Connection: keep-alive

%s
EOL;
        protected static $response_status_text = array(200=>'OK',404=>'NOT FOUND');

        protected static $response_content = array(404=>'page not found');

        public function __construct($request=''){
            $this->request = $request;
        }

        public function generate_response(){
            return $this->request?$this->process_ok():$this->process_404();
        }

        protected function process_ok(){
            //遍历变量
            foreach($this->request->vars as $k=>$v){
                $$k = $v;
            }
            //适配模板
            $file = BASE_DIR.DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR.$this->request->template;
            //模板解析
            ob_start();
            @include($file);
            $file_content = ob_get_contents();
            ob_end_clean();
            return $this->return_response($file_content);
        }

        protected function process_404(){
            return $this->return_response('',404);
        }

        protected function return_response($content='',$status_code = 200){
            $time = $this->return_time();
            $status_text = self::$response_status_text[$status_code];
            $reply_text = $status_code==200?$content:self::$response_content[$status_code];
            $result = sprintf(self::$response_format,$status_code,$status_text,$time,$time,$reply_text);
            return $result;
        }

        protected function return_time(){
            return  date('D, d M Y h:i:s',time());
        }
    }